package code.parser;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import code.generation.CodeGeneration;
import code.generation.FieldSerializeJava;


public class Struct extends Snippet {
	
	public static void main(String[] args) {
		final Struct struct = new Struct(new File(CodeGeneration.currentClassPath,
				"MatchVSDefines.h"));
		List<Struct> list = struct.regularExpressionMatch(struct.source);
		for (Struct struct2 : list) {
			System.out.println(new FieldSerializeJava().serialize(struct2));
		}
	}
	public String namespace;
	public Map<String, String> defineMap = new HashMap<String, String>();
	public Struct(){
		super();
	}
	public Struct(File file) {
		super(file);
	}
	public Struct(String source) {
		super(source);
	}
	public List<Field> fieldList ;
	@Override
	public List<Struct> regularExpressionMatch(String source) {
		
		source = replaceDefine(defineMap,source);
		List<Struct> structList = new ArrayList<Struct>();
		StringBuilder sb = new StringBuilder();
		sb.append("typedef\\s+");
		sb.append("struct\\s+");
		sb.append("([a-z_][a-z0-9_]*?)");
		sb.append("\\s*\\{");
		sb.append("([\\s\\S]*?)");
		sb.append("\\}\\s*([a-z_][a-z0-9_]*?)\\s*;");
		
		Pattern p = Pattern.compile(sb.toString(),
				Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
		Matcher m = p.matcher(source);
		while (m.find()) {
			Struct struct = new Struct();
			struct.name = m.group(1);
			struct.source = m.group(2);
			struct.fieldList = new Field().regularExpressionMatch(struct.source);
			structList.add(struct);
			System.out.println(struct.name);
			System.out.println(struct.source);
			System.out.println("_________");
		}
		
		return structList;
	
	}
	private static String replaceDefine(Map<String, String> defineMap,
			String txt) {
		Set<String> set = defineMap.keySet();
		for (String define : set) {

			final String replacement = defineMap.get(define);
			txt = txt.replace(define, replacement == null ? "" : replacement);
		}
		return txt;
	}
}
